#案例：把某接口的响应数据（json）写入到文件中！
#需求：把GET http://127.0.0.1:8000/api/departments/接口查询到的N个学院信息写入到文件中！

import requests,json


#发请求
r=requests.get(url="http://127.0.0.1:8000/api/departments/")
#获取该接口的响应实体(json)
response_body=r.json()

#拿到所有学院
# allXueyuan=response_body["results"]
# for dept in allXueyuan:
#     dept_Str=json.dumps(dept).encode('utf-8').decode('unicode_escape')
#
#     #把deptStr写入到文件中
#     with open('data1.txt', 'a', encoding='utf-8') as f:
#         f.write(dept_Str)
#         f.write("\n")


#每行效果：ID:xxxx,Name:xxx,Master:xxx,kouhao:xxx
allXueyuan=response_body["results"]
for dept in allXueyuan:
    #{'dep_id': 'T20011N', 'dep_name': 'Test201学院', 'master_name': 'Master201', 'slogan': 'Slogan201'}
    dept_id=dept["dep_id"]
    dept_name=dept["dep_name"]
    master=dept["master_name"]
    kouhao=dept["slogan"]

    t="ID:{},Name:{},Master:{},kouhao:{}".format(dept_id,dept_name,master,kouhao)
    with open('data2.txt', 'a', encoding='utf-8') as f:
        f.write(t)
        f.write("\n")


